package cn.mcartoon.smsdemo.utils.sms;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.aliyuncs.http.MethodType;

import java.util.HashMap;
import java.util.Map;

/**
 * 阿里云短信发送
 */
@Component
public class SendSms {

    Logger log = LoggerFactory.getLogger(SendSms.class);

    @Autowired
    private AliSmsConfig aliSmsConfig;


    /**
     * 发送单条短信
     *
     * @param phone
     * @param code
     */
    public String send(String phone, String code) {
        String result = null;
        DefaultProfile profile = DefaultProfile.getProfile("default", aliSmsConfig.getAccessKeyId()
                , aliSmsConfig.getAccessKeySecret());
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest Request = new CommonRequest();
        CommonResponse response = null;
        Request.setMethod(MethodType.POST);
        Request.setDomain(aliSmsConfig.getDomain());
        Request.setVersion(aliSmsConfig.getVersion());
        Request.setAction("SendSms");
        Request.putQueryParameter("RegionId", aliSmsConfig.getRegionId());
        Request.putQueryParameter("PhoneNumbers", phone);
        Request.putQueryParameter("SignName", aliSmsConfig.getSignName());
        Request.putQueryParameter("TemplateCode", aliSmsConfig.getTemplateCode());
        Map<String, String> map = new HashMap<>();
        map.put("code", code);
        Request.putQueryParameter("TemplateParam", JSON.toJSONString(map));
        try {
            response = client.getCommonResponse(Request);
            log.info("阿里云发送短信返回值：{}", response.getData());
            // {"Message":"OK","requestId":"B1A53065-B1EF-5AF5-8365-B8665E0549FF","bizId":"261608906632527495^0","Code":"OK"}
            JSONObject jsonObject = JSON.parseObject(response.getData());
            result = jsonObject.get("Message").toString();
        } catch (ServerException e) {
            log.error("阿里云发送短信失败，服务端错误：{}", e);
        } catch (ClientException e) {
            log.error("阿里云发送短信失败，客户端错误：{}", e);
        }
        return result;
    }


    public static void main(String[] args) {

        // Please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set.
        /** use STS Token
         DefaultProfile profile = DefaultProfile.getProfile(
         "<your-region-id>",           // The region ID
         System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),       // The AccessKey ID of the RAM account
         System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),   // The AccessKey Secret of the RAM account
         System.getenv("ALIBABA_CLOUD_SECURITY_TOKEN"));     // STS Token
         **/

        DefaultProfile profile =
                DefaultProfile.getProfile("default", "LTAI5tM83UYxNZdKeF9ZHKZw", "1Lo61zsYI3dCsO0Z5thh8TQD7sIkWS");
        IAcsClient client = new DefaultAcsClient(profile);


        SendSmsRequest request = new SendSmsRequest();
        request.setSignName("pilipili漫画");
        request.setTemplateCode("SMS_465130068");
        request.setPhoneNumbers("19231232205");
        request.setTemplateParam("{\"code\":\"1234\"}");

        try {
            SendSmsResponse response = client.getAcsResponse(request);
            System.out.println(new Gson().toJson(response));
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
        }
    }
}